import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import Nabar from '../../conpoment/Nabar';
import styles from './index.module.css';

// 药品数据接口
interface DrugItem {
  id: number;
  name: string;
  price: number;
  quantity: number;
  tags: string[];
  type: 'medicine' | 'check' | 'test';
  description?: string;
  maxQuantity?: number;
  isPrescription?: boolean;
}

// 就诊人数据接口
interface Patient {
  id: number;
  name: string;
  idNumber: string;
}

// 购物车数据接口
interface CartData {
  cart: { [key: number]: number };
  products: DrugItem[];
}

function Index() {
  const nav = useNavigate();
  const location = useLocation();
  const [reason, setReason] = useState('');
  const [showPatientModal, setShowPatientModal] = useState(false);
  const [selectedPatient, setSelectedPatient] = useState<Patient>({
    id: 1,
    name: '王小柯',
    idNumber: '2015****10'
  });
  const [cartItems, setCartItems] = useState<DrugItem[]>([]);
  
  // 模拟就诊人数据
  const patients: Patient[] = [
    { id: 1, name: '王小柯', idNumber: '2015****10' },
    { id: 2, name: '李玲玲', idNumber: '2015****10' }
  ];

  // 从路由状态获取购物车数据
  useEffect(() => {
    const cartData = location.state as CartData;
    if (cartData && cartData.cart && cartData.products) {
      // 根据购物车数据生成申请项目列表
      const items: DrugItem[] = [];
      Object.entries(cartData.cart).forEach(([productId, quantity]) => {
        const product = cartData.products.find(p => p.id === parseInt(productId));
        if (product && quantity > 0) {
          items.push({
            ...product,
            quantity: quantity
          });
        }
      });
      setCartItems(items);
    } else {
      // 如果没有购物车数据，使用默认数据（用于测试）
      const defaultItems: DrugItem[] = [
        {
          id: 1,
          name: '新冠预防中药 (正常人群)',
          price: 11.80,
          quantity: 1,
          tags: ['处方药', '限购5剂'],
          type: 'medicine',
          description: '功效:主要提高免疫力,预防新冠疾病',
          maxQuantity: 5,
          isPrescription: true
        },
        {
          id: 2,
          name: '云南白药胶囊 0.5g*20片',
          price: 10.08,
          quantity: 1,
          tags: ['处方药'],
          type: 'medicine',
          description: '功效:化瘀止血,活血止痛',
          isPrescription: true
        }
      ];
      setCartItems(defaultItems);
    }
  }, [location.state]);

  // 计算总价
  const totalPrice = cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);

  // 处理申请原因输入
  const handleReasonChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const value = e.target.value;
    if (value.length <= 200) {
      setReason(value);
    }
  };

  // 处理确认申请
  const handleConfirm = () => {
    if (reason.length < 20) {
      alert('申请原因不能少于20字');
      return;
    }
    
    // 构建新订单数据
    const newOrder = {
      items: cartItems.map(item => ({
        id: item.id,
        name: item.name,
        type: item.type,
        price: item.price,
        quantity: item.quantity,
        unit: item.type === 'medicine' ? '剂' : '次',
        tags: item.tags
      })),
      hospital: '四川省保健院北苑',
      amount: totalPrice,
      patientName: selectedPatient.name,
      patientId: selectedPatient.idNumber,
      applicationReason: reason
    };
    
    console.log('确认申请', { reason, cartItems, totalPrice, selectedPatient });
    
    // 跳转到开单记录页面，传递新订单数据
    nav('/self_jl', { 
      state: { 
        newOrder: newOrder 
      } 
    });
  };

  // 处理选择就诊人
  const handlePatientSelect = (patient: Patient) => {
    setSelectedPatient(patient);
    setShowPatientModal(false);
  };

  // 处理添加就诊人
  const handleAddPatient = () => {
    console.log('添加就诊人');
    // 这里可以添加跳转到添加就诊人页面的逻辑
    setShowPatientModal(false);
  };

  return (
    <div className={styles.container}>
      {/* 顶部导航栏 */}
      <Nabar title="开单确认" sticky={false} />
      
      {/* 右侧图标 */}
      <div className={styles.headerRight}>
        <div className={styles.headerIcon}>⋯</div>
        <div className={styles.headerIcon}>◎</div>
      </div>

      <div className={styles.content}>
        {/* 申请信息部分 */}
        <div className={styles.section}>
          <div className={styles.sectionTitle}>申请信息</div>
          <div className={styles.infoRow}>
            <span className={styles.infoLabel}>申请医院</span>
            <span className={styles.infoValue}>四川省保健院北苑</span>
          </div>
          <div className={styles.infoRow}>
            <span className={styles.infoLabel}>申请人</span>
            <span 
              className={styles.infoValue} 
              onClick={() => setShowPatientModal(true)}
            >
              {selectedPatient.name} &gt;
            </span>
          </div>
        </div>

        {/* 申请原因部分 */}
        <div className={styles.section}>
          <div className={styles.sectionTitle}>
            申请原因<span className={styles.required}>*</span>
          </div>
          <div className={styles.reasonContainer}>
            <div className={styles.decorativeIcons}>
              <div className={styles.diamond}></div>
              <div className={styles.diamond}></div>
            </div>
            <textarea
              className={styles.reasonInput}
              placeholder="请输入项目申请原因用于医生更准确判断,不少于20字"
              value={reason}
              onChange={handleReasonChange}
              maxLength={200}
            />
            <div className={styles.charCount}>{reason.length}/200</div>
          </div>
        </div>

        {/* 申请项目部分 */}
        <div className={styles.section}>
          <div className={styles.sectionTitle}>申请项目</div>
          <div className={styles.drugList}>
            {cartItems.length > 0 ? (
              cartItems.map((item) => (
                <div key={item.id} className={styles.drugItem}>
                  <div className={styles.drugHeader}>
                    <div className={styles.drugTypeTag}>
                      {item.type === 'medicine' ? '药' : item.type === 'check' ? '检' : '验'}
                    </div>
                    <div className={styles.drugName}>{item.name}</div>
                    <div className={styles.drugPrice}>¥{(item.price * item.quantity).toFixed(2)}</div>
                  </div>
                  <div className={styles.drugDetails}>
                    <div className={styles.drugQuantity}>数量: {item.quantity}{item.type === 'medicine' ? '剂' : '项'}</div>
                    <div className={styles.drugTags}>
                      {item.tags.map((tag, index) => (
                        <span 
                          key={index} 
                          className={`${styles.tag} ${
                            tag.includes('处方') ? styles.prescriptionTag : styles.limitTag
                          }`}
                        >
                          {tag}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className={styles.emptyCart}>
                <div className={styles.emptyText}>购物车为空</div>
                <div className={styles.emptySubText}>请先选择要申请的项目</div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 选择就诊人模态框 */}
      {showPatientModal && (
        <div className={styles.modalOverlay} onClick={() => setShowPatientModal(false)}>
          <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
            <div className={styles.modalDragHandle}></div>
            <div className={styles.modalHeader}>
              <div className={styles.modalTitle}>选择就诊人</div>
              <div 
                className={styles.modalClose}
                onClick={() => setShowPatientModal(false)}
              >
                ×
              </div>
            </div>
            <div className={styles.patientList}>
              {patients.map((patient) => (
                <div
                  key={patient.id}
                  className={`${styles.patientItem} ${
                    selectedPatient.id === patient.id ? styles.selectedPatient : ''
                  }`}
                  onClick={() => handlePatientSelect(patient)}
                >
                  <div className={styles.patientName}>{patient.name}</div>
                  <div className={styles.patientId}>{patient.idNumber}</div>
                </div>
              ))}
            </div>
            <div className={styles.modalFooter}>
              <button 
                className={styles.addPatientBtn}
                onClick={handleAddPatient}
              >
                添加就诊人
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 底部确认按钮 */}
      <div className={styles.footer}>
        <button 
          className={styles.confirmBtn}
          onClick={handleConfirm}
          disabled={reason.length < 20}
        >
          确认申请
        </button>
      </div>
    </div>
  );
}
export default Index;